﻿#region Header
//************************************************************************************
// Name: DMSAppService
// Description: class used to implement Document related methods
// Created On:  27-Dec-2011
// Created By:  Swathi
// Last Modified On:
// Last Modified By: 
// Last Modified Reason: 
//*************************************************************************************
#endregion Header
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Chinook.Facade.ViewModel;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Management;
using Chinook.Facade.Messaging;
using Base.Common;
using Chinook.Facade.Ioc;


namespace Chinook.Facade
{
    public class DMSAppService : IDMSAppService
    {
        //Property to hold IDmsDao
        private IDmsDao _dmsDao;

        /// <summary>
        /// Property to get instance for DMSDao
        /// </summary>
        public IDmsDao DMSDao
        {
            get
            {
                //check whether the dms dao object is not null
                if (_dmsDao != null)
                    //return the object
                    return _dmsDao;
                //get the object from Facade exposer
                _dmsDao = new FacadeExposer().DMSDao;
                //return dms dao Object
                return _dmsDao;
            }
        }

        /// <summary>
        /// Method used to get Files from Directory
        /// </summary>
        /// <param name="documentsRequest"></param>
        /// <returns></returns>
        public DocumentsResponse GetFilesFromDirectory(DocumentsRequest documentsRequest)
        {
            //declare instance to hold document response
            var docResponse = new DocumentsResponse();
            //declare instance to hold document view model list
            IList<DocumentViewModel> lstFiles = new List<DocumentViewModel>();
            //try
            try
            {               
                //get files from filesystem daoa by passing directory path
                var files = DMSDao.GetFiles(documentsRequest.DirPath);
                //loop for each file in directory
                foreach (var fi in files)
                {
                    var ext = "";
                    //geth the file extension of the file
                    if (fi.Extension.Length > 1)
                        ext = fi.Extension.Substring(1).ToLower();
                    //declare instance to document view model
                    var file = new DocumentViewModel();
                    //assign document Name
                    file.DocumentName = fi.Name;
                    //assign document created date
                    file.DateCreated = fi.CreationTime;
                    //assign file size
                    file.Size = GetFileSize((int)fi.Length);
                    //get the access control of file to know owner of the file
                    FileSecurity fileSecurity = fi.GetAccessControl();
                    //assign file owner
                    file.Owner = fileSecurity.GetOwner(typeof(NTAccount)).ToString();
                    //check whether the file is read only or not
                    if (fi.IsReadOnly)
                    {
                        file.Permissions = "Read/Write";
                    }
                    else
                    {
                        file.Permissions = "Read";
                    }
                    //assign category as ext
                    file.Category = ext;
                    //add the record to the files list
                    lstFiles.Add(file);
                }
                //assign document view models to response
                docResponse.DocumentsViewModel = lstFiles;
                //set response success as true
                docResponse.Success = true;
            }
            //catch in case of exception
            catch (Exception ex)
            {
                //set response success as false
                docResponse.Success = false;
                //set response message as exception message 
                docResponse.Message = ex.Message;
            }
            //return document response
            return docResponse;
        }

        /// <summary>
        /// Method used to get file size in terms of KB, MB, or GB
        /// </summary>
        /// <param name="byteCount"></param>
        /// <returns></returns>
        private string GetFileSize(double byteCount)
        {
            //declare default string size in term of bytes
            string size = "0 Bytes";
            //check whethre the bytes count id greater than or equal to 1073741824.0
            if (byteCount >= 1073741824.0)
                //format the file size in terms of GB
                size = String.Format("{0:##.##}", byteCount / 1073741824.0) + " GB";
            //check whethre the bytes count id greater than or equal to 1048576.0
            else if (byteCount >= 1048576.0)
                //format the file size in terms of MB
                size = String.Format("{0:##.##}", byteCount / 1048576.0) + " MB";
            //check whethre the bytes count id greater than or equal to 1024.0
            else if (byteCount >= 1024.0)
                //format the file size in terms of KB
                size = String.Format("{0:##.##}", byteCount / 1024.0) + " KB";
            //check whethre the bytes count id greater than zero and less than 1024.0
            else if (byteCount > 0 && byteCount < 1024.0)
                //format the file size in terms of Bytes
                size = byteCount.ToString() + " Bytes";
            //return file size
            return size;
        }

        /// <summary>
        /// Method used to get the file owner
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private string GetFileOwner(string path)
        {
            //Declare instance to hold Management object 
            ManagementObject mgmt = new ManagementObject("Win32_LogicalFileSecuritySetting.path='" + path + "'");
            //Invoke Management Base object  method GetSecurityDescriptor
            ManagementBaseObject secDesc = mgmt.InvokeMethod("GetSecurityDescriptor", null, null);
            //get the Descriptor as Management Base object
            ManagementBaseObject descriptor = secDesc.Properties["Descriptor"].Value as ManagementBaseObject;
            //get the Owner as Management Base object
            ManagementBaseObject owner = descriptor.Properties["Owner"].Value as ManagementBaseObject;
            //return Owner name with Domain
            return owner.Properties["Domain"].Value.ToString() + "\\" + owner.Properties["Name"].Value.ToString();

        }

    }
}
